package com.china08.yxyapi.api.comm.sws;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.util.DateUtils;
import com.google.gson.Gson;

@CrossOrigin
@RestController
public class TeachingPerPackStatisticsDataCrtController {

    private static final Logger LOGGER = Logger.getLogger(TeachingPerPackStatisticsDataCrtController.class);

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/api_yw/comm/sws/teaching/perpack/crt", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(HttpServletRequest request, HttpServletResponse response) throws ParseException {

        long dayCount = DateUtils.difference(DateUtils.formatStrDate4(20170401), new Date());
        Long count = new Long(dayCount);

        Long cha = 0l;
        for (int i = count.intValue(); i > 0; i -= cha) {
            cha = DateUtils.difference(DateUtils.getMothOfFirstDay(DateUtils.subtractDay(new Date(), i)),
                    DateUtils.getMothOfLastDay(DateUtils.subtractDay(new Date(), i))) + 1;
            Integer context = DateUtils.formatDate4(DateUtils.subtractDay(new Date(), i));
            getPerPackForUser(context);
        }
    }

    private void getPerPackForUser(Integer day) throws ParseException {
        Date dayDate = DateUtils.formatStrDate4(day);
        Date startDate = DateUtils.getMothOfFirstDay(dayDate);
        Date endDate = DateUtils.getMothOfLastDay(dayDate);

        Criteria criteria = Criteria.where("createdDate").gte(startDate).lte(endDate);

        // 获取考试信息
        TypedAggregation<YxyLecturePrePack> aggregation = Aggregation.newAggregation(YxyLecturePrePack.class,
                Aggregation.match(criteria),
                Aggregation.group("userId", "schoolId")//
                        .count().as("count")//
                        .first("schoolId").as("schoolId")//
                        .first("schoolNick").as("schoolNick")//
                        .first("userId").as("userId"));

        AggregationResults<UserPerPackModel> result = mongoTemplate.aggregate(aggregation, UserPerPackModel.class);
        List<UserPerPackModel> userPerPackModellLst = result.getMappedResults();
        List<UserPerPackModel> sendDataLst = new ArrayList<UserPerPackModel>();

        Integer index = 0;
        for (UserPerPackModel userPackModel : userPerPackModellLst) {

            sendDataLst.add(userPackModel);
            index++;
            if (index == 100) {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                    headers.setContentType(type);
                    headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                    Gson gson = new Gson();
                    StringBuffer objectBuffer = new StringBuffer();
                    objectBuffer.append("{");
                    objectBuffer.append("\"userPerPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                    objectBuffer.append("\"dateTime\":" + DateUtils.formatDate6(dayDate));
                    objectBuffer.append("}");
                    HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                    String httpResult = restTemplate.postForObject(
                            yxyApiYxUrl + "/comm/school/sws/teaching/teacher/perpack/month", formEntity, String.class);
                    if (httpResult.contains("success")) {
                        System.out.println("getPerPackForUser方法执行ok");
                    }
                } catch (Exception e) {
                    LOGGER.info("getPerPackForUser方法执行错误：" + e.getMessage());
                }
                sendDataLst = new ArrayList<UserPerPackModel>();
                index = 0;
            }
        }
        if (sendDataLst.size() > 0) {
            try {
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                Gson gson = new Gson();
                StringBuffer objectBuffer = new StringBuffer();
                objectBuffer.append("{");
                objectBuffer.append("\"userPerPackModelLst\":" + gson.toJson(sendDataLst) + ",");
                objectBuffer.append("\"dateTime\":" + DateUtils.formatDate6(dayDate));
                objectBuffer.append("}");
                HttpEntity<String> formEntity = new HttpEntity<String>(objectBuffer.toString(), headers);
                String httpResult = restTemplate.postForObject(
                        yxyApiYxUrl + "/comm/school/sws/teaching/teacher/perpack/month", formEntity, String.class);
                if (httpResult.contains("success")) {
                    System.out.println("getPerPackForUser方法执行ok");
                }
            } catch (Exception e) {
                LOGGER.info("getPerPackForUser方法执行错误：" + e.getMessage());
            }
        }
    }

    protected static class UserPerPackModel {
        public Long count;

        public String schoolId;
        public String schoolNick;
        public String userId;
    }
}
